package com.starinside.wp.service.chat;

import com.starinside.wp.handler.ChatKefuListener;
import com.starinside.wp.listener.OpenAIEventSourceListener;
import com.unfbx.chatgpt.OpenAiStreamClient;
import com.unfbx.chatgpt.entity.chat.ChatCompletion;
import com.unfbx.chatgpt.entity.chat.Message;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

@Service
public class GPTQuestionServiceImpl implements IQuestionService {

    private static OpenAiStreamClient openAiStreamClient;

    private static String OPENAI_API_HOST = "http://huahua8.online/";

    //常公子
    private static String OPENAI_API_KEY = "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";


    //
    static {
//        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger());
//        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        openAiStreamClient = OpenAiStreamClient.builder()
                .apiKey(Arrays.asList(OPENAI_API_KEY))
//                .connectTimeout(50)
//                .writeTimeout(50)
//                .readTimeout(50)
                .apiHost(OPENAI_API_HOST)
                .build();
    }


    @Override
    public void sseQuestion(List<Message> messages, OpenAIEventSourceListener openAIEventSourceListener){

        //设置3.5版本
        ChatCompletion chatCompletion = ChatCompletion.builder()
                .model(ChatCompletion.Model.GPT_3_5_TURBO_16K_0613.getName())
//                    .maxTokens(218).temperature(0.6)
                .messages(messages)
                .build();

        openAiStreamClient.streamChatCompletion(chatCompletion, openAIEventSourceListener);
    }

    @Override
    public String getSysQuestionString( List<Message> messages ) {
        //开始对话 .maxTokens(512)
        ChatCompletion chatCompletion = ChatCompletion.builder().messages(messages).model("gpt-3.5-turbo").build();

        CountDownLatch latch = new CountDownLatch(1);
        ChatKefuListener listener = new ChatKefuListener(latch, messages);

        try {
            openAiStreamClient.streamChatCompletion(chatCompletion, listener);
            latch.await();
        } catch (RuntimeException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        String result = listener.getBuffer().stream().collect(Collectors.joining());

        return result;
    }
}
